/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved. 
 */
package com.icinfo.cloud.provider.punish.actscode.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.DocumentKindEnum;
import com.icinfo.cloud.provider.punish.actscode.dto.ActsCodeDto;
import com.icinfo.cloud.provider.punish.actscode.mapper.CaseActsCodeErrInfoMapper;
import com.icinfo.cloud.provider.punish.actscode.model.CaseActsCodeErrInfo;
import com.icinfo.cloud.provider.punish.actscode.service.ICaseActsCodeErrInfoService;
import com.icinfo.cloud.provider.punish.actscode.service.ICaseActsCodeInfoService;
import com.icinfo.cloud.provider.punish.common.documentoperate.service.IStageDocCommonOperateService;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigBusiParamDocumentInfoMapper;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.config.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseMainInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseDocumentRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseDocumentRecordService;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述: 处罚赋码失败记录表 case_acts_code_err_info 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2023年03月08日
 */
@Service
public class CaseActsCodeErrInfoServiceImpl extends MyBatisServiceSupport implements ICaseActsCodeErrInfoService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(CaseActsCodeErrInfoServiceImpl.class);

    @Autowired
    private CaseActsCodeErrInfoMapper caseActsCodeErrInfoMapper;
    @Autowired
    private ICaseActsCodeInfoService caseActsCodeInfoService;
    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    private ICaseDocumentRecordService caseDocumentRecordService;
    @Resource
    private ConfigBusiParamDocumentInfoMapper configBusiParamDocumentInfoMapper;
    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;
    @Resource
    private ISysDepartParamService sysDepartParamService;
    @Resource
    private IStageDocCommonOperateService stageDocCommonOperateService;

    /**
     * 赋码失败日志保存
     * @author liyafeng
     * @date 2023/3/8
      * @param caseId
     * @param errMsg
     * @return
     */
    @Override
    public void saveCaseActsCodeErrInfo(String caseId, String errMsg) {
        CaseActsCodeErrInfo caseActsCodeErrInfo=new CaseActsCodeErrInfo();
        caseActsCodeErrInfo.setId(StringUtils.uuid());
        caseActsCodeErrInfo.setAddTime(new Date());
        //默认未处理
        caseActsCodeErrInfo.setDealStatus(Constant.STRING_0);
        caseActsCodeErrInfo.setErrMsg(errMsg);
        caseActsCodeErrInfo.setCaseId(caseId);
        caseActsCodeErrInfoMapper.insert(caseActsCodeErrInfo);
    }
    /**
     * 赋码失败重新赋码
     * @author liyafeng
     * @date 2023/3/8
      * @param
     * @return {@link int}
     */
    @Override
    public int reSaveCaseActsCodeInfo() {
        Example example=new Example(CaseActsCodeErrInfo.class);
        example.createCriteria().andEqualTo("dealStatus",Constant.STRING_0);
        List<CaseActsCodeErrInfo> caseActsCodeErrInfos=caseActsCodeErrInfoMapper.selectByExample(example);
        caseActsCodeErrInfos.forEach(caseActsCodeErrInfo->{
            try {
                String caseId=caseActsCodeErrInfo.getCaseId();
                ActsCodeDto actsCodeDto=new ActsCodeDto();
                actsCodeDto.setCaseId(caseId);
                int num=caseActsCodeInfoService.saveCaseActsCodeInfo(actsCodeDto);
                if(num>0){
                    //重新赋码后 重新生成审批表
                    //1.重新查询案件信息
                    CaseMainInfo caseMainInfo=caseMainInfoMapper.selectByPrimaryKey(caseId);
                    String caseType=caseMainInfo.getCaseType();
                    String documentType="";
                    if(caseType.equals(CaseTypeEnum.NORMAL_PROCEDURE.getCode())){
                        documentType=Constant.PTCX;
                    }else if(caseType.equals(CaseTypeEnum.SIMPLE_PROCEDURE.getCode())){
                        documentType=Constant.JYCX;
                    }
                    //重新生成文书
                    rebuildPdf(caseId,caseMainInfo,documentType);

                }
                CaseActsCodeErrInfo updateCaseActsCodeErrInfo=new CaseActsCodeErrInfo();
                updateCaseActsCodeErrInfo.setId(caseActsCodeErrInfo.getId());
                updateCaseActsCodeErrInfo.setDealStatus(Constant.STRING_1);
                updateCaseActsCodeErrInfo.setErrMsg(Constant.STRING_SUCCESS_EN);
                caseActsCodeErrInfoMapper.updateByPrimaryKeySelective(updateCaseActsCodeErrInfo);
            }catch (Exception e){
                CaseActsCodeErrInfo updateCaseActsCodeErrInfo=new CaseActsCodeErrInfo();
                updateCaseActsCodeErrInfo.setId(caseActsCodeErrInfo.getId());
                updateCaseActsCodeErrInfo.setDealStatus(Constant.STRING_1);
                updateCaseActsCodeErrInfo.setErrMsg(e.getMessage());
                caseActsCodeErrInfoMapper.updateByPrimaryKeySelective(updateCaseActsCodeErrInfo);
            }

        });
        return 1;
    }

    private void rebuildPdf(String caseId, CaseMainInfo caseMainInfo,String documentType) {
        //2.查询立案审批表文书信息
        Example configExample=new Example(ConfigBusiParamDocumentInfo.class);
        if(Constant.JYCX.equals(documentType)){
            configExample.createCriteria().andEqualTo("busiParamId",caseMainInfo.getBusiParamId()).andEqualTo("documentKindCode", DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode()).andEqualTo("isDeleted",Constant.STRING_0);
        }else{
            configExample.createCriteria().andEqualTo("busiParamId",caseMainInfo.getBusiParamId()).andEqualTo("documentKindCode", DocumentKindEnum.DOC_KIND_LASPB.getCode()).andEqualTo("isDeleted",Constant.STRING_0);
        }

        List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfos=configBusiParamDocumentInfoMapper.selectByExample(configExample);

        if(!ObjectUtils.isEmpty(configBusiParamDocumentInfos)){
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo=configBusiParamDocumentInfos.get(0);
            CaseDocumentRecord caseDocumentRecord=caseDocumentRecordService.getCaseDocumentRecord(caseId,configBusiParamDocumentInfo.getDocumentCatalogCode());
            String documentContent=caseDocumentRecord.getDocumentContent();
            Map<String,Object> dataMap = JSON.parseObject(documentContent, HashMap.class);
            dataMap.put("barCodeUrl",caseMainInfo.getCaseBarCodeUrl());
            dataMap.put("qrCodeUrl",caseMainInfo.getCaseQrCodeUrl());
            CaseDocumentRecord updateCaseDocumentRecord=new CaseDocumentRecord();
            updateCaseDocumentRecord.setId(caseDocumentRecord.getId());
            updateCaseDocumentRecord.setDocumentContent(JSONObject.toJSON(dataMap).toString());
            int updateNum=caseDocumentRecordMapper.updateByPrimaryKeySelective(updateCaseDocumentRecord);
            if(updateNum>0){
                SysDepartParam sysDepartParam=sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(caseMainInfo.getCaseOrgCode(),caseMainInfo.getCaseDeptCode());
                Map<String, Object> paramMap=new HashMap<>(8);
                JSONObject object=new JSONObject();
                object.put("documentId",caseDocumentRecord.getId());
                object.put("uniscid",sysDepartParam.getUnicode());
                JSONArray jsonArray=new JSONArray();
                jsonArray.add(object);
                paramMap.put("documentInfo",jsonArray);
                paramMap.put("documentType",documentType);
                stageDocCommonOperateService.rebuildPdf(paramMap);
            }
        }
    }
}